package aps

import org.json.JSONObject

/**
 * app更新
 */
class UpGradeAppController {

    def grailsApplication

    def versionControlFile = "updateControl2.0.ini"

    /**
     * 使用方法：
     * 1.登录时触发事件，检测pda版本号与服务器发布的app版本号
     * 2.发布的apk文件，必须放在目录中,切最外层的目录必须和服务器程序在同级
     * 3.版本控制文件路径updateControl.ini，与aps后台服务在同一目录
     * 4.index (入参：version 版本号,file:下载的文件路径和文件名)返回校验信息如下：
     msg.name = "upGradeAPP"  消息id
     msg.version = version    版本号
     msg.info = ""            消息
     msg.file = ""            升级文件路径
     msg.date = ""            日期
     msg.alert = "false"      是否弹窗
     msg.downLoadURL = ""     文件下载路径
     * 5.如果校验有新版本,提示下载信息，下载URL：
     * window.open(base+"/"+json.downLoadURL)
     * 示例：bas + '/'+ 'UpGradeApp/downLoadFile?file=updateAPK\\aps2.0.apk'
     * 6.updateControl.ini版本控制文件必须与下所示格式一致
     * version=2.0,file=updateAPK\aps1.0.apk,date=Fri Feb 02 03:26:43 CST 2018
     *
     * @return
     */
    def index() {

        def standardJSONForPDA = JSONObject.newInstance()
        standardJSONForPDA.put("code", "-200")
        standardJSONForPDA.put("message", "")
        standardJSONForPDA.put("data", null)

        def version = params.version ?: "1.0"
        def file = params.file ?: "updateAPK\\aps1.0.apk"
        def absoluteDir = absoluteDir()
//        println   "${absoluteDir + versionControlFile + " " + Calendar.getInstance().getTime()}"
        def controlFile = new File(absoluteDir + versionControlFile)
        def msg = [:]
        msg.name = "upGradeAPP"
        msg.version = version
        msg.info = ""
        msg.file = file
        msg.date = "${new Date()}"
        msg.alert = "false"
        msg.downLoadURL = ""

        def dir = new File(absoluteDir + "updateAPK")
        if (!dir.exists() && !dir.isFile()) {
            dir.mkdir()
        }

        if (!controlFile.exists()) {
            controlFile.createNewFile()
            controlFile.withWriter { out ->
                out.append("version=${version},file=${file},date=${msg.date}")
            }
        } else {
            def msgStr = ""
            controlFile.eachLine { stream ->
                msgStr = stream
            }
            if (msgStr.indexOf("version=${version}") < 0) {
                msgStr = msgStr.split(",")
                msgStr.each { it ->
                    def data = it.split("=")
                    msg."${data[0]}" = data[1]
                }
                msg.info = "有新版本请更新后使用!"
                msg.alert = true
                msg.downLoadURL = "updateAPK/${msg.file}"
                standardJSONForPDA.put("code", "200")
            }
        }
        standardJSONForPDA.put("data", msg)
        //println standardJSONForPDA.toString()
        render standardJSONForPDA.toString()
    }

    /**
     *
     def downLoadFile() {def standardJSONForPDA = JSONObject.newInstance()
     standardJSONForPDA.put("code","-200")
     standardJSONForPDA.put("message","下载更新异常!")
     standardJSONForPDA.put("data",null)


     try{def absoluteDir = absoluteDir()
     def file = params.file ?: "updateAPK\\aps1.0.apk"

     def downName = file.substring(file.lastIndexOf("\\") + 1, file.length())
     downName = URLEncoder.encode(downName, "UTF-8");
     def absoluteFile = new File( absoluteDir + file)
     if (absoluteFile.exists()) {response.setHeader("Content-disposition", "attachment;filename=${downName}")
     response.contentType = "application/octet-stream"
     response.setCharacterEncoding("utf-8")
     def out = response.getOutputStream()
     def is = absoluteFile.newInputStream()
     def buf = new byte[1024 * 2]
     def len = 0
     while ((len = is.read(buf)) > 0) {out.write(buf, 0, len)}out.flush()
     out.close()
     is.close()
     standardJSONForPDA.put("code","200")}}catch ( Exception e){e.printStackTrace()}finally{render standardJSONForPDA.toString()}}*
     *
     */


    def absoluteDir() {
        def absolutePath = grailsApplication.getMainContext().servletContext.getRealPath("")
        def index = absolutePath.lastIndexOf("\\")
        def absoluteDir = absolutePath.substring(0, index)
        index = absoluteDir.lastIndexOf("\\")
        absoluteDir = absoluteDir.substring(0, index + 1)
    }

}
